import React, {
  FC, useState,
} from 'react';
import { useQuery } from 'react-query';
import { Loading, OverflowWrap } from '@choerodon/components';
import { useFormatCommon } from '@choerodon/master';
import { Menu } from 'choerodon-ui';
import { get } from '@choerodon/inject';
import { useUnmount, useDebounceFn } from 'ahooks';
import { handleBuildModal } from '@/routes/app-pipeline/routes/app-pipeline-edit/components/pipeline-modals/build-modals';
import { handleCustomModal } from '@/routes/app-pipeline/routes/app-pipeline-edit/components/pipeline-modals/custom-modal';
import {
  MAVEN_BUILD,
} from '@/routes/app-pipeline/CONSTANTS';
import './index.less';
import useGetJobPanel from '../../../../hooks/useGetJobPanel';
import { templateJobsApi } from '@/api/template-jobs';
import useTabData from '@/routes/app-pipeline/routes/app-pipeline-edit/hooks/useTabData';
import { TAB_BASIC, TAB_ADVANCE_SETTINGS, TAB_FLOW_CONFIG } from '@/routes/app-pipeline/routes/app-pipeline-edit/stores/CONSTANTS';
import usePipelineContext from '@/routes/app-pipeline/hooks/usePipelineContext';

export type JobTypesPanelProps = {
  handleJobAddCallback:(addonData: any)=>(editData:any)=>void
  handlePanelClickCallback:()=>void
  handleBlur:any
  stageIndex: any,
}

const {
  SubMenu,
  Item,
} = Menu;

const handlePipelineModal = ({
  data,
  callback,
  advancedData,
  level,
  title,
  modalProps,
  extraProps,
}: any) => {
  switch (level) {
    case 'project': {
      if (window.location.href.includes('project-pipeline-template')) {
        handleBuildModal(data, callback, advancedData, level, title, modalProps);
      } else if ([
        // 'audit'人工卡点
        'audit',
        //  chart_deploy chart包
        'chart_deploy',
        // 部署组
        'deployment_deploy',
        // 主机部署
        'host_deploy',
        // api测试
        'api_test',
        // maven_build为ci任务
        MAVEN_BUILD].includes(data?.type)) {
        handleBuildModal(data, callback, advancedData, level, title, modalProps, extraProps);
      } else if (data?.type.includes('cd_')) {
        handleBuildModal(data, callback, undefined, undefined, '添加任务');
      } else {
        handleCustomModal(data, callback, title);
      }

      break;
    }
    default: {
      handleBuildModal(data, callback, advancedData, level, title, modalProps, extraProps);
    }
  }
};

const prefixCls = 'c7ncd-job-types-panel';

const JobTypesPanel:FC<JobTypesPanelProps> = (props) => {
  const {
    handleJobAddCallback,
    handlePanelClickCallback,
    handleBlur,
    stageIndex,
  } = props;

  const {
    run,
  } = useDebounceFn((data: any) => {
    setSubMenuId(data);
  }, {
    wait: 300,
  });

  useUnmount(() => {
    handleBlur();
  });

  const panels = useGetJobPanel();
  const [currentSelectedSubMenuId, setSubMenuId] = useState('');
  const [_data, _setdata, getTabData] = useTabData();

  const {
    level,
    jobPanelApiCallback,
    configuration,
  } = usePipelineContext();

  const getSubMenuChild = ({ queryKey }:any) => {
    const [_key, subMenuId] = queryKey;
    if (level === 'project') {
      return templateJobsApi.getJobByGroupId(subMenuId);
    }
    return jobPanelApiCallback?.(subMenuId);
  };

  const { data: childrenMenus, isLoading, isFetching } = useQuery(['sub-menu-child', currentSelectedSubMenuId], getSubMenuChild, {
    enabled: !!currentSelectedSubMenuId,
  });

  const formatCommon = useFormatCommon();

  const handleClick = (data: any) => {
    const { keyPath } = data;
    const stepData = JSON.parse(keyPath[0]);
    const categoryData = JSON.parse(keyPath[1]);
    handlePanelClickCallback();
    const flowData = getTabData(TAB_FLOW_CONFIG);
    const stageList = flowData[stageIndex]?.jobList;
    let addData = {
      data: {
        ...stepData,
        groupType: categoryData?.type,
        configuration,
      },
      callback: handleJobAddCallback(stepData),
      advancedData: getTabData(TAB_ADVANCE_SETTINGS),
      level,
      extraProps: {
        stageData: flowData,
        jobIndex: stageList?.length,
        stageIndex,
      },
    };
    if (stageList) {
      const flag = stageList.find((i: any) => {
        const stageName = i?.name;
        const addName = addData?.data?.name;
        return stageName === addName;
      });
      if (flag) {
        addData = {
          ...addData,
          data: {
            ...addData.data,
            name: `${addData.data.name}_${Math.floor(Math.random() * 10 + 1)}`,
          },
        };
      }
    }
    handlePipelineModal(addData);
  };

  const renderChildrenMenu = ({ parentId }:{
    parentId:string
  }) => {
    if (String(parentId) !== String(currentSelectedSubMenuId)) {
      return null;
    }
    if (isLoading || isFetching) {
      return <Loading type={get('configuration.master-global:loadingType') || 'c7n'} style={{ height: '50px' }} />;
    }
    if (!childrenMenus?.length) {
      return (
        <div className={`${prefixCls}-subMenu-empty`}>
          {formatCommon({ id: 'nodata' })}
        </div>
      );
    }
    return childrenMenus?.map((item:any) => {
      const {
        id, name,
      } = item;
      let concatItem = item;
      // 这里可能因为之前流水线只在project层 这里加了流水线模板的判断 之前的逻辑保留 不然会造成添加任务 名称都覆盖成了流水线的名称
      if (level === 'project' && !window.location.href.includes('project-pipeline-template')) {
        concatItem = {
          ...item,
          ...getTabData(TAB_BASIC),
          image: item?.image || getTabData(TAB_BASIC)?.image,
        };
      }
      return (
        <Item key={JSON.stringify(concatItem)}>
          <OverflowWrap
            width={128}
            tooltipsConfig={{
              title: name,
            }}
          >
            {name}
          </OverflowWrap>
        </Item>
      );
    });
  };

  const renderSubMenus = () => panels?.map((item: { id: any; name: any; type: any; }) => {
    const { id, name, type } = item;
    return (
      <SubMenu
        key={JSON.stringify(item)}
        title={name}
        // onTitleClick={() => {
        //   setSubMenuId(id);
        // }}
        onMouseEnter={() => run(id)}
        className={`${prefixCls}-subMenu`}
      >
        {renderChildrenMenu({ parentId: id })}
      </SubMenu>
    );
  });

  return (
    <Menu onClick={handleClick} style={{ width: 160 }} mode="vertical">
      {renderSubMenus()}
    </Menu>
  );
};

export default JobTypesPanel;

export { handlePipelineModal };
